package com.vision.sales.sv.report;

import java.util.HashMap;
import java.util.Map;

import com.vision.sales.cm.data.Month;
import com.vision.sales.cm.db.data.Customer;

/**
 * 
 * @author Mark
 *
 */
public class CustomerSalesRow implements Comparable<CustomerSalesRow> {
	
	public static final String GROSS_SALES = "Gross Sales";
	public static final String DISCOUNTS = "Discounts";
	public static final String NET_AMOUNT = "Net Amount";
	
	public static final String[] COLUMNS = { GROSS_SALES, DISCOUNTS, NET_AMOUNT};

	private String customerName;
	private Customer customer;
	private Map<String, Double> salesMap;
	
	public CustomerSalesRow(String header) {
		this.customerName = header;
		this.salesMap = new HashMap<String, Double>();
	}
	
	public CustomerSalesRow(Customer customer, boolean useCode) {
		this(useCode ? customer.getCode() : customer.getName());
		this.customer = customer;
	}

	public Object get(String column) {
		if ("customer".equals(column))
			 return this.customerName;
		
		if ("address".equals(column)) 
			return customer != null ? customer.getAddress() : "";
		if ("tin".equals(column))
			return customer != null ? customer.getTin() : "";
		
		return salesMap.get(column);
	}
	
	public Customer getCustomer() {
		return customer;
	}

	public String getCustomerName() {
		return customerName;
	}
	
	public Map<String, Double> getSalesMap() {
		if (salesMap == null)
			salesMap = new HashMap<String, Double>();
		return salesMap;
	}
	
	public void computeAnnualTotal() {
		double total = 0;
		for (String month : Month.MONTHS) {
			Double value = getSalesMap().get(month);
			if (value != null)
				total += value;
			else
				getSalesMap().put(month, 0d);
		}
		
		getSalesMap().put("total", total);
	}
	
	public void computeMonthlyTotal() {
		double netAmount = 0;
		
		Double value = getSalesMap().get(GROSS_SALES);
		if (value != null)
			netAmount += value;
		else
			getSalesMap().put(GROSS_SALES, 0d);
		
		Double discounts = getSalesMap().get(DISCOUNTS);
		if (discounts != null)
			netAmount -= discounts;
		else
			getSalesMap().put(DISCOUNTS, 0d);
		
		getSalesMap().put(NET_AMOUNT, netAmount);
	}
	
	@Override
	public int compareTo(CustomerSalesRow r) {
		return customerName.compareToIgnoreCase(r.customerName);
	}

}
